<?php
/**
 * User: YL
 * Date: 2019/6/10
 */

namespace restful;

use restful\cipher\Runtime;
use restful\traits\InstanceTrait;
use restful\utils\Dispatch;
use restful\utils\Env;

class RuntimeCipher
{
    use InstanceTrait;

    protected $isDebug;
    protected $controller;

    private function __construct()
    {
        $module = Env::get('runtime.module', '');
        $this->controller = Env::get('runtime.controller', '');
        $this->isDebug = Env::get('request.' . $module . '_debug', true);
    }

    /**
     * 请求
     * @return mixed
     */
    public function request()
    {
        $res = [];

        // 非调试模式
        if (! $this->isDebug) {
            // 获取调度信息
            [$controller] = Dispatch::get();

            // 不需要加密的类
            $noNeedCipherClass = $controller->getNoNeedCipherClass();

            // 需要解密
            if (! in_array($this->controller, $noNeedCipherClass)) {
                // 请求参数
                $params = $controller->getRequest()->param('params', '');
                // 加密配置
                $config = Env::get('request.' . $_ENV['runtime_module']);
                $res = json_decode(trim(Runtime::getInstance($config)
                        ->decrypt($params)), true) ?? [];
            } else {
                // 返回请求参数
                $res = $controller->getParams();
            }
        }

        return $res;
    }

    /**
     * 响应
     * @param array $response
     * @return mixed
     */
    public function response(array $response)
    {
        // 非调试模式
        if (! $this->isDebug) {
            // 获取调度信息
            [$controller] = Dispatch::get();
            // 不需要加密的类
            $noNeedCipherClass = $controller->getNoNeedCipherClass();

            // 需要加密
            if (! in_array($this->controller, $noNeedCipherClass)) {
                // 加密配置
                $config = Env::get('request.' . $_ENV['runtime_module']);
                $response = Runtime::getInstance($config)
                    ->encrypt(json_encode($response));
            }
        }

        return $response;
    }
}